﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Interop = Microsoft.Office.Interop;
using Tools = Microsoft.Office.Tools;
using System.Windows.Controls;
using System.Windows;
using System.Windows.Media;

namespace FarpacHelper
{
    public partial class MainWindow
    {
        ToolCollection g_Toolstring;

        //private DataFormat format = DataFormats.GetDataFormat("DragDropItemsControl");
        double _tsLengthCM = 0;
        double _tsMaxOD = 0;
        double _tsMinOD = double.MaxValue;
        //============================================================================================================================//
        const double LEN_PIXEL_PER_CM = 2;
        const double OD_PIXEL_PER_CM = 8;
        double _lenPXperCM = LEN_PIXEL_PER_CM;
        double _odPXperCM = OD_PIXEL_PER_CM;
        //============================================================================================================================//
        private void RedrawToolstring()
        {
            double tsMaxLengthPx = listTS.ActualHeight - 40;
            double tsMaxODPx = listTS.ActualWidth - 10;
            //double tsLengthPx = _tsLengthCM * PIXEL_PER_CM;
            if (_tsLengthCM * LEN_PIXEL_PER_CM < tsMaxLengthPx)
            {   // Total Length Pixel < listView Length Pixel => Restore Original Scale
                _lenPXperCM = LEN_PIXEL_PER_CM;
            }
            else
            {   // Total Length > listView Length => Decrease Scale
                _lenPXperCM = tsMaxLengthPx / _tsLengthCM;
            }

            if (_tsMaxOD * OD_PIXEL_PER_CM < tsMaxODPx)
            {   // Total OD Pixel < listView Width Pixel => Restore Original Scale
                _odPXperCM = OD_PIXEL_PER_CM;
            }
            else
            {   // Total OD Pixel > listView Width Pixel => Decrease Scale
                _odPXperCM = tsMaxODPx / _tsMaxOD;
            }

            foreach (Tool tool in g_Toolstring.ToolstringDiagram)
            {
                tool.RenderHeight = (int)(tool.LengthCM * _lenPXperCM);
                tool.RenderWidth = (int)(tool.DiameterCM * _odPXperCM);
            }
        }
        //============================================================================================================================//
        // Implement later to see ScrollViewer
        public static DependencyObject GetScrollViewer(DependencyObject depObj)
        {
            if (depObj is ScrollViewer)
            { return depObj; }
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
            {
                var child = VisualTreeHelper.GetChild(depObj, i);
                var result = GetScrollViewer(child);
                if (result == null) { continue; }
                else { return result; }
            }
            return null;
        }

    }

    public class Helper
    {
        #region Public Property
        public ToolCollection ToolCollection { get; private set; }
        public IEnumerable<Preset> PresetCollection { get; private set; }
        public IEnumerable<RunIH> RunCollection { get; private set; }
        #endregion
        //============================================================================================================================//
        Tools.Excel.Workbook g_Farpac;
        private Tools.Excel.Worksheet g_tsSheet;
        private Tools.Excel.Worksheet g_dbSheet;
        //============================================================================================================================//
        public Helper(Tools.Excel.Workbook farpac)
        {
            g_Farpac = farpac;
            g_tsSheet = xls.getSheet(g_Farpac, "Toolstring");
            g_dbSheet = xls.getSheet(g_Farpac, "Database");
            // ToolCollection
            ToolCollection = new ToolCollection(ReadTools(g_dbSheet));
            // PresetCollection
            try
            {
                PresetCollection = ReadPresets(g_dbSheet);
                // RunCollection
                RunCollection = ReadRuns(g_tsSheet);
            }
            catch (Exception e) {
                MessageBox.Show(e.Message,"Fail to Read Preset & Run !");
                //PresetCollection = new Preset[0];
                //RunCollection = new RunIH[0];
            }
        }
        //============================================================================================================================//
        //============================================================================================================================//
        //============================================================================================================================//
        const int NAME_COLUMN = 3, SIZE_COLUMN = 0, DESCRIPTION_COLUMN = 4, LENGTH_COLUMN = 6, OD_COLUMN = 8, WEIGHT_COLUMN = 9, IMAGE_COLUMN = 11, XBEGIN_COLUMN = 12, XEND_COLUMN = 13;
        private IEnumerable<Tool> ReadTools(Tools.Excel.Worksheet dbSheet)
        {
            System.Globalization.CultureInfo Oldci = System.Threading.Thread.CurrentThread.CurrentCulture;
            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");

            try
            {
                int iRow = 0, iBlank = 0; List<Tool> list = new List<Tool>();
                while (iBlank < 5) // Khi nao Blank tren 5 row lien tiep thi Quit Loop
                {
                    // iRow++;
                    // Neu Blank thi cu tang iBlank
                    //Tools.Excel.Worksheet dbSheetVSTO = Tools.Excel.Worksheet.GetVstoObject(dbSheet);

                    if (xls.IsBlankCell(dbSheet, ++iRow, NAME_COLUMN)) iBlank++;
                    else
                    {
                        iBlank = 0; // Neu co chu thi Reset iBlank bat dau dem lai
                        // Doc Name
                        string name = xls.ReadString(dbSheet, iRow, NAME_COLUMN); // Khong Trim() neu nhap file Excel du ky tu space thi may se bao loi.
                        if (name.StartsWith(" ") | name.EndsWith(" "))
                        {
                            MessageBoxResult res = MessageBox.Show(string.Format("Found useless SPACE of NAME in R{0}C{1}, sheet Database of Farpac.xlsx : \"{2}\"\r\n" +
                            "I will replace those useless space for you now. Click OK to continue ...", iRow.ToString(), NAME_COLUMN.ToString(), name), "SPACE at BEGIN or END of NAME");
                            if (res == MessageBoxResult.OK) { xls.WriteString(dbSheet, iRow, NAME_COLUMN, name); name = name.Trim(); } // Trim inside HERE will match between Farpac & Code. So when fill back to Diagram will match with DataValidation for String Cell.
                        }

                        if (name != "Name")
                        {   // If Name khong phai Title thi Read
                            Uri uri = new Uri("ImagesToolstring\\" + xls.ReadString(dbSheet, iRow, IMAGE_COLUMN), UriKind.Relative);
                            string desc = xls.ReadString(dbSheet, iRow, DESCRIPTION_COLUMN);
                            double len = xls.ReadDouble(dbSheet, iRow, LENGTH_COLUMN); if (len == 0) len = 640;
                            double od = xls.ReadDouble(dbSheet, iRow, OD_COLUMN);
                            double xbegin = xls.ReadDouble(dbSheet, iRow, XBEGIN_COLUMN);
                            double xend = xls.ReadDouble(dbSheet, iRow, XEND_COLUMN);
                            Tool tool = new Tool(name, "2in", "XXXXXX", "SAPXXXXX", uri, xbegin, xend, 30, 30,
                                length: len.ToString("0.###") + "cm", diameter: od.ToString("0.###") + "cm", description: desc);
                            list.Add(tool);
                        }
                    }
                }
                return list;
            }
            catch (Exception e) { throw new Exception("ReadTools FAIL !", e); }
            finally { System.Threading.Thread.CurrentThread.CurrentCulture = Oldci; }
        }
        //============================================================================================================================//
        const int PRESET_COLUMN = 15, PRESET_ROW = 105;
        private IEnumerable<Preset> ReadPresets(Tools.Excel.Worksheet dbSheet)
        {
            System.Globalization.CultureInfo Oldci = System.Threading.Thread.CurrentThread.CurrentCulture;
            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");

            try
            {
                int iCol = PRESET_COLUMN; int iBlankCol = 0; List<Preset> pList = new List<Preset>();
                while (iBlankCol < 5)
                {
                    if (xls.IsBlankCell(dbSheet, PRESET_ROW, iCol)) { iBlankCol++; iCol++; }
                    else
                    {  // Column Not Blank
                        iBlankCol = 0; // Reset iBlankCol

                        int iRow = PRESET_ROW;

                        string presetName = xls.ReadString(dbSheet, iRow++, iCol); // Read PresetName then Increase Row 1 to Start Read Tool
                        int iBlankRow = 0; List<string> tList = new List<string>();
                        while (iBlankRow < 5) // Khi nao Blank tren 5 row lien tiep thi Quit Loop
                        {
                            // iRow++;
                            // Neu Blank thi cu tang iBlank
                            //Tools.Excel.Worksheet dbSheetVSTO = Tools.Excel.Worksheet.GetVstoObject(dbSheet);

                            if (xls.IsBlankCell(dbSheet, iRow, iCol)) { iBlankRow++; iRow++; }
                            else
                            {
                                iBlankRow = 0; // Neu co chu thi Reset iBlank bat dau dem lai
                                // Doc Tool Name
                                string tName = xls.ReadString(dbSheet, iRow, iCol); // Khong Trim() neu nhap file Excel du ky tu space thi may se bao loi.
                                if (tName.StartsWith(" ") | tName.EndsWith(" "))
                                {
                                    MessageBoxResult res = MessageBox.Show(string.Format("Found useless SPACE of NAME in R{0}C{1}, sheet Database of Farpac.xlsx : \"{2}\"\r\n" +
                                    "I will replace those useless space for you now. Click OK to continue ...", iRow.ToString(), iCol.ToString(), tName), "SPACE at BEGIN or END of NAME");
                                    if (res == MessageBoxResult.OK) { xls.WriteString(dbSheet, iRow, iCol, tName); tName = tName.Trim(); } // Trim inside HERE will match between Farpac & Code. So when fill back to Diagram will match with DataValidation for String Cell.
                                }

                                // Read Tool Name and add to ToolList
                                tList.Add(tName);
                                iRow++;
                            }
                        }
                        // Finish Read 1 Preset Column
                        Preset preset = new Preset(presetName, tList.ToArray());
                        pList.Add(preset); // Add Preset to Preset List
                        iCol++;
                    }
                }
                // Finish Read All Preset Column
                return pList;
            }
            catch (Exception e) { throw new Exception("ReadPresets FAIL !", e); }
            finally { System.Threading.Thread.CurrentThread.CurrentCulture = Oldci; }
        }
        //============================================================================================================================//
        const int RUN_COLUMN = 4, RUN_ROW = 4, TOOL_ROW = 11, TOOL_ROW_END = 41;
        private IEnumerable<RunIH> ReadRuns(Tools.Excel.Worksheet tsSheet)
        {
            System.Globalization.CultureInfo Oldci = System.Threading.Thread.CurrentThread.CurrentCulture;
            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");

            try
            {
                int iCol = RUN_COLUMN; int iBlankCol = 0; List<RunIH> rList = new List<RunIH>();
                while (iBlankCol < 5)
                {
                    if (xls.IsBlankCell(tsSheet, RUN_ROW, iCol)) { iBlankCol++; iCol++; }
                    else
                    {  // Column Not Blank
                        iBlankCol = 0; // Reset iBlankCol

                        int runNumber = xls.ReadInteger(tsSheet, RUN_ROW, iCol);
                        string runName = xls.ReadString(tsSheet, RUN_ROW + 1, iCol);
                        int iRow = TOOL_ROW; int iBlankRow = 0; List<string> tList = new List<string>();
                        while (iBlankRow < 5) // Khi nao Blank tren 5 row lien tiep thi Quit Loop
                        {
                            // iRow++;
                            // Neu Blank thi cu tang iBlank
                            //Tools.Excel.Worksheet dbSheetVSTO = Tools.Excel.Worksheet.GetVstoObject(dbSheet);

                            if (xls.IsBlankCell(tsSheet, iRow, iCol)) { iBlankRow++; iRow++; }
                            else
                            {
                                iBlankRow = 0; // Neu co chu thi Reset iBlank bat dau dem lai
                                // Doc Tool Name
                                string tName = xls.ReadString(tsSheet, iRow, iCol); // Khong Trim() neu nhap file Excel du ky tu space thi may se bao loi.
                                if (tName.StartsWith(" ") | tName.EndsWith(" "))
                                {
                                    MessageBoxResult res = MessageBox.Show(string.Format("Found useless SPACE of NAME in R{0}C{1}, sheet Database of Farpac.xlsx : \"{2}\"\r\n" +
                                    "I will replace those useless space for you now. Click OK to continue ...", iRow.ToString(), iCol.ToString(), tName), "SPACE at BEGIN or END of NAME");
                                    if (res == MessageBoxResult.OK) { xls.WriteString(tsSheet, iRow, iCol, tName); tName = tName.Trim(); } // Trim inside HERE will match between Farpac & Code. So when fill back to Diagram will match with DataValidation for String Cell.
                                }

                                // Read Tool Name and add to ToolList
                                tList.Add(tName);
                                iRow++;
                            }
                        }
                        // Finish Read 1 Run Column
                        RunIH run = new RunIH(runNumber, runName, tList, iCol);
                        rList.Add(run); // Add RunIH to Run List
                        iCol++;
                    }
                }
                // Finish Read All Run Column
                return rList;
            }
            catch (Exception e) { throw new Exception("ReadPresets FAIL !", e); }
            finally { System.Threading.Thread.CurrentThread.CurrentCulture = Oldci; }
        }
        //============================================================================================================================//
        //============================================================================================================================//
        //============================================================================================================================//
        /// <summary>
        /// Reread the Database for ToolCollection & PresetCollection
        /// </summary>
        public void RefreshDatabase()
        {
            ToolCollection = new ToolCollection(ReadTools(g_dbSheet));
            PresetCollection = ReadPresets(g_dbSheet);
        }
        //============================================================================================================================//
        public void RefreshRun()
        {
            RunCollection = ReadRuns(g_tsSheet);
        }
        //============================================================================================================================//
        public bool WriteRun(RunIH run, ItemCollection tools)
        {
            System.Globalization.CultureInfo Oldci = System.Threading.Thread.CurrentThread.CurrentCulture;
            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
            try
            {
                //RunIH rih = cbRunNo.SelectedItem as RunIH;

                // Clear Old First
                int iRow; bool writeOK = true;
                for (iRow = TOOL_ROW; iRow <= TOOL_ROW_END; iRow++)
                {
                    if (xls.WriteString(g_tsSheet, iRow, run.ColumnXLS, "") == false) writeOK = false;
                }
                if (writeOK) run.ToolString.Clear();
                else { MessageBox.Show("Fail to Write this RUN " + run.Number.ToString()); return false; } // Reread this Run further Implement

                // Start Write New
                iRow = TOOL_ROW;
                foreach (Tool tool in tools)
                {
                    if (xls.WriteString(g_tsSheet, iRow++, run.ColumnXLS, tool.Name))
                        run.ToolString.Add(tool.Name); // If Write Success then Update the comboBox Item Run
                }

                return true;
            }
            catch (Exception ex) { throw new Exception("WriteTools FAIL !", ex); }
            finally { System.Threading.Thread.CurrentThread.CurrentCulture = Oldci; }
        }
    }
}
